/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

var plistloaded = false;

var unUploadImages = 0;

var edProductId = false;

var edProductImages = [];

var ZXXFILEPD = false;

$(function() {
    Loading.finish();
    ajaxLoadProductList();
});

/**
 * 加载商品数据列表
 * @param {type} page
 * @returns {undefined}
 */
function ajaxLoadProductList(page) {
    if (!plistloaded) {
        var page = page || 0;
        wpLoading();
        $.post('?/Wdmin/ajaxLoadProductList', {}, function(res) {
            Loading.finish();
            $('#card5st1-productlist').html(res);
            $('.wd-productlist').hover(function() {
                $(this).find('.wd-pdl-edit').addClass('hover');
            }, function() {
                $(this).find('.wd-pdl-edit').removeClass('hover');
            }).unbind('click').click(function() {
                // 商品编辑点击
                c52_pdinfo(parseInt($(this).attr('data-id')));
                // 切换到tab1
                subTabSwitch(1);
            });
            __resize__();
            plistloaded = true;
        });
    }
}

function c5tab2onload() {
    ajaxLoadProductList();
}

/**
 * tab2 onload
 * @returns {undefined}
 */
function c5tab1onload() {
    uep = UE.getEditor('ueditorp', {
        autoHeight: false,
        minFrameWidth: 200
    });
    uep.ready(function() {
        uep.setHeight(document.documentElement.clientHeight - productEditHeight);
        ueploaded = true;
        // c52_pdinfo(parseInt(7862));
    });
    // 图片已经上传过了。
    $('#gmess-send-btn-pd').unbind('click').click(function() {
        // before check
        if (unUploadImages === 0) {
            __ProductAlterFinish();
        } else {
            if ($('#pd-form-title').val() !== '') {
                $("#fileSubmit-pd")[0].click();
            }
        }
    });

    if (!ZXXFILEPD) {
        var params = {
            fileInput: $("#fileImage-pd")[0],
            dragDrop: $("#fileDragArea-pd").get(0),
            upButton: $("#fileSubmit-pd").get(0),
            url: '?/vProduct/ImageUpload',
            filter: function(files) {
                var arrFiles = [];
                for (var i = 0, file; file = files[i]; i++) {
                    if (file.type.indexOf("image") === 0) {
                        if (file.size >= 512000) {
                            Alert('您这张"' + file.name + '"图片大小过大，应小于500k');
                        } else {
                            arrFiles.push(file);
                        }
                    } else {
                        Alert('文件"' + file.name + '"不是图片。');
                    }
                }
                return arrFiles;
            },
            onSelect: function(files, index) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    $('#pd-images-list').append('<img class="pd-images add" src="' + e.target.result + '" />');
                    $('#appmsg_thumb-pd').hide();
                    $('#appmsimg-preview-pd').attr('src', e.target.result).show();
                    // 未上传
                    unUploadImages++;
                };
                reader.readAsDataURL(files[index]);
            },
            onDelete: function(file) {
                ZXXFILEPD.funDeleteFile(file.index);
            },
            onDragOver: function() {
                $(this).addClass("upload_drag_hover");
            },
            onDragLeave: function() {
                $(this).removeClass("upload_drag_hover");
            },
            onProgress: function(file, loaded, total) {

            },
            onSuccess: function(file, response) {
                var res = response.toJson();
                edProductImages.push('product_hpic2__' + res.imagename);
                if (--unUploadImages === 0) {
                    // 全部上传完毕
                    __ProductAlterFinish();
                }
            },
            onFailure: function(file) {

            },
            onComplete: function() {

            }
        };
        ZXXFILEPD = $.extend(ZXXFILE, params);
        ZXXFILEPD.init();
    }
}

/**
 * 加载商品详细数据
 * @param {type} id
 * @param {type} __callback
 * @returns {undefined}
 */
function c52_pdinfo(id, __callback) {
    wpLoading();
    $.get('?/WdminAjax/ajaxGetProductInfo/id=' + id, function(r) {
        r = r.toJson();
        edProductId = parseInt(r.product_id);
        $('#pd-form-title').val(r.product_name);
        $('#pd-form-desc').val(r.product_subtitle);
        $('#pd-form-cat').val(r.product_cat);
        $('#pd-form-prices').val(r.sale_prices);
        $('#pd-form-discount').val(r.discount);
        uep.setContent('');
        if (r.product_desc) {
            uep.setContent(r.product_desc);
        }
        edProductImages.length = 0;

        // 如果有图片
        if (r.images.length > 0) {
            $('#appmsg_thumb-pd').hide();
            $('#appmsimg-preview-pd').attr('src', shoproot + 'static/product_hpic/' + r.images[0].image_path).show();
            $('#fileDragArea-pd').height($('#appmsimg-preview-pd').height());
            var ig = 0, _str = '';
            for (ig in r.images) {
                ig = parseInt(ig);
                edProductImages.push(r.images[ig].image_path);
                if (ig !== 0) {
                    // images
                    _str += '<a class="pd-imgwap"><i class="pd-imgdel" rel-path="' + r.images[ig].image_path + '"></i><img class="pd-images" src="'
                            + shoproot
                            + 'static/product_hpic/'
                            + r.images[ig].image_path + '" /></a>';
                }
            }
        }
        
        $('#pd-images-list').html(_str);
        $('.pd-imgdel').unbind('click').click(function() {
            fnDeleteImage($(this).attr('rel-path'), this);
        });
        // 执行回调
        if (typeof __callback !== 'undefined') {
            __callback();
        }
        $('#pd-delete-wp').css('display', 'block');
        $('#pd-delete-btn').unbind('click').click(__ProductDelete);
        $('#gmess-edit-return-btn').unbind('click').click(__ProductEditFinish);
        Loading.finish();
    });
}

function fnDeleteImage(_path, node) {
    for (var p in edProductImages) {
        if (edProductImages[p] === _path) {
            delete edProductImages[p];
            $(node).parent().remove();
            break;
        }
    }
}

/**
 * 删除商品
 * @returns {undefined}
 */
function __ProductDelete() {
    if (confirm('你确定要删除吗，删除不可恢复')) {
        $.post(shoproot + '?/WdminAjax/deleteProduct/', {
            id: edProductId
        }, function(res) {
            if (res == 1) {
                plistloaded = false;
                Alert('删除成功');
                ajaxLoadProductList();
                __ProductEditFinish();
            } else {
                Alert('删除失败');
            }
        });
    }
}

/**
 * 商品编辑结束
 * @returns {undefined}
 */
function __ProductEditFinish() {
    $('#pd-delete-wp').hide();
    $('#pd-form-prices,#pd-form-title').val();
    $('#appmsimg-preview-pd').attr('src', '').hide();
    $('#appmsg_thumb-pd').show();
    $('#uploadForm-pd')[0].reset();
    $('#pd-images-list').html('');
    $('#fileDragArea-pd').css('height', 'auto');
    uep.setContent('');
    subTabSwitch(2);
}

/**
 * 商品编辑结束
 * @returns {undefined}
 */
function __ProductAlterFinish() {
    var title = $('#pd-form-title').val();
    var price = $('#pd-form-prices').val();
    var discount = $('#pd-form-discount').val();
    var desc = uep.getContent();
    var subtitle = $('#pd-form-desc').val();
    var images = edProductImages;

    // [HttpPost]
    $.post(shoproot + '?/WdminAjax/updateProduct', {
        product_id: !edProductId ? 0 : edProductId,
        product_name: title,
        product_prices: price,
        product_discount: discount,
        product_desc: desc,
        product_subtitle: subtitle,
        product_images: images,
        product_cat: $('#pd-form-cat').val()
    }, function(r) {
        if (r === '1') {
            edProductImages.length = 0;
            ZXXFILE.fileFilter.length = 0;
            __ProductEditFinish();
            Alert('保存成功');
        } else {
            Alert('保存失败');
        }
    });
}

/**
 * 删除待上传图片
 * @param {type} path
 * @returns {undefined}
 */
function fnDeleteUmg(path) {
    // edProductImages
}